package ulmermark.demo.rest.spring;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.View;

import ulmermark.demo.protobuf.OrderProtos;
import ulmermark.demo.protobuf.OrderProtos.Order.Builder;

public class OrdersProtobufView implements View{
	private static final Logger LOGGER = Logger.getLogger(OrdersProtobufView.class);

	@Override
	public String getContentType() {
		// TODO Auto-generated method stub
		return "application/x-protobuf";
	}


	@Override
	public void render(Map<String, ?> model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
//		LOGGER.debug(model);
//		LOGGER.debug(request);
//		LOGGER.debug(response);
		
		
		List<Order> orders = (List<Order>) model.get("orders");		

		ulmermark.demo.protobuf.OrderProtos.Orders.Builder ordersBuilder = OrderProtos.Orders.newBuilder();
		
		Builder orderBuilder = OrderProtos.Order.newBuilder();
		
		for( Order order:orders){
			orderBuilder.setClientName(order.getClientName()).setAmount(order.getAmount()).setId(order.getId()).build();
			ordersBuilder.addOrder(orderBuilder.build());
			orderBuilder.clear();
		}
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ordersBuilder.build().writeTo(baos);
		
//		LOGGER.debug(baos.toString());
		response.getOutputStream().write(baos.toByteArray());
	}
}
